<template>
  <div class="connection-status-indicator">
    <!-- 简洁状态指示器 -->
    <div
      class="status-badge"
      :class="statusClass"
      @click="showDetails = !showDetails"
      :title="statusTooltip"
    >
      <div class="status-dot" :class="statusClass"></div>
      <!-- <span class="status-text">{{ statusText }}</span> -->
    </div>

    <!-- 详细信息面板 -->
    <transition name="fade">
      <div v-if="false" class="status-details">
        <div class="detail-header">
          <h4>连接状态</h4>
          <button @click="showDetails = false" class="close-btn">×</button>
        </div>

        <div class="detail-content">
          <!-- 行情连接状态 -->
          <div class="connection-item">
            <div class="item-header">
              <span class="item-label">行情连接</span>
              <span class="item-status" :class="getMdStatusClass()">
                {{ getMdStatusText() }}
              </span>
            </div>
            <div v-if="lastMdDisconnectReason" class="item-detail">
              <span class="detail-label">断线原因:</span>
              <span class="detail-value">{{ lastMdDisconnectReason.text }}</span>
            </div>
            <div v-if="lastMdDisconnectTime" class="item-detail">
              <span class="detail-label">断线时间:</span>
              <span class="detail-value">{{ formatTime(lastMdDisconnectTime) }}</span>
            </div>
          </div>

          <!-- 交易连接状态 -->
          <div class="connection-item">
            <div class="item-header">
              <span class="item-label">交易连接</span>
              <span class="item-status" :class="getTraderStatusClass()">
                {{ getTraderStatusText() }}
              </span>
            </div>
            <div v-if="lastTraderDisconnectReason" class="item-detail">
              <span class="detail-label">断线原因:</span>
              <span class="detail-value">{{ lastTraderDisconnectReason.text }}</span>
            </div>
            <div v-if="lastTraderDisconnectTime" class="item-detail">
              <span class="detail-label">断线时间:</span>
              <span class="detail-value">{{ formatTime(lastTraderDisconnectTime) }}</span>
            </div>
          </div>

          <!-- 连接历史 -->
          <div v-if="showHistory" class="connection-history">
            <div class="history-header">
              <span>连接历史</span>
              <button @click="clearHistory" class="clear-btn">清除</button>
            </div>
            <div class="history-list">
              <div
                v-for="(record, index) in connectionHistory"
                :key="index"
                class="history-item"
              >
                <span class="history-time">{{ formatTime(record.timestamp) }}</span>
                <span class="history-type">{{
                  record.type === "md" ? "行情" : "交易"
                }}</span>
                <span class="history-status" :class="record.status">
                  {{ record.status === "connected" ? "连接" : "断开" }}
                </span>
                <span v-if="record.reason_text" class="history-reason">
                  {{ record.reason_text }}
                </span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button @click="toggleHistory" class="action-btn">
              {{ showHistory ? "隐藏历史" : "显示历史" }}
            </button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import {
  useConnectionMonitor,
  ConnectionStatus,
} from "../composables/useConnectionMonitor";

const {
  mdStatus,
  traderStatus,
  overallStatus,
  hasConnectionIssue,
  lastMdDisconnectReason,
  lastTraderDisconnectReason,
  lastMdDisconnectTime,
  lastTraderDisconnectTime,
  reconnectAttempts,
  getConnectionHistory,
  clearConnectionHistory,
  onConnectionChange,
  manualReconnect,
} = useConnectionMonitor();

const showDetails = ref(false);
const showHistory = ref(false);
const connectionHistory = ref([]);

// 计算状态类
const statusClass = computed(() => {
  if (overallStatus.value === ConnectionStatus.CONNECTED) {
    return "status-connected";
  } else if (overallStatus.value === ConnectionStatus.RECONNECTING) {
    return "status-reconnecting";
  } else if (overallStatus.value === ConnectionStatus.CONNECTING) {
    return "status-connecting";
  } else {
    return "status-disconnected";
  }
});

// 状态文本
const statusText = computed(() => {
  console.log("overallStatus", overallStatus.value, ConnectionStatus);
  if (overallStatus.value === ConnectionStatus.CONNECTED) {
    return "已连接";
  } else if (overallStatus.value === ConnectionStatus.RECONNECTING) {
    return `重连中(${reconnectAttempts.value})`;
  } else if (overallStatus.value === ConnectionStatus.CONNECTING) {
    return "连接中";
  } else {
    return "已断开";
  }
});

// 状态提示
const statusTooltip = computed(() => {
  if (overallStatus.value === ConnectionStatus.RECONNECTING) {
    return `正在尝试重连... (第${reconnectAttempts.value}次)`;
  }
  if (hasConnectionIssue.value) {
    const issues = [];
    if (mdStatus.value === ConnectionStatus.DISCONNECTED) {
      issues.push("行情连接断开");
    }
    if (traderStatus.value === ConnectionStatus.DISCONNECTED) {
      issues.push("交易连接断开");
    }
    return issues.join(", ");
  }
  return "系统连接正常";
});

// 获取行情状态类
function getMdStatusClass() {
  return mdStatus.value === ConnectionStatus.CONNECTED ? "status-ok" : "status-error";
}

// 获取行情状态文本
function getMdStatusText() {
  if (mdStatus.value === ConnectionStatus.CONNECTED) return "正常";
  if (mdStatus.value === ConnectionStatus.RECONNECTING) return "重连中";
  if (mdStatus.value === ConnectionStatus.CONNECTING) return "连接中";
  return "断开";
}

// 获取交易状态类
function getTraderStatusClass() {
  return traderStatus.value === ConnectionStatus.CONNECTED ? "status-ok" : "status-error";
}

// 获取交易状态文本
function getTraderStatusText() {
  if (traderStatus.value === ConnectionStatus.CONNECTED) return "正常";
  if (traderStatus.value === ConnectionStatus.RECONNECTING) return "重连中";
  if (traderStatus.value === ConnectionStatus.CONNECTING) return "连接中";
  return "断开";
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return "-";
  const date = new Date(timestamp);
  return date.toLocaleString("zh-CN", {
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
}

// 切换历史显示
function toggleHistory() {
  showHistory.value = !showHistory.value;
  if (showHistory.value) {
    updateHistory();
  }
}

// 更新历史记录
function updateHistory() {
  connectionHistory.value = getConnectionHistory(20);
}

// 清除历史
function clearHistory() {
  clearConnectionHistory();
  connectionHistory.value = [];
}

// 连接状态变化监听
let unsubscribe = null;

onMounted(() => {
  // 监听连接状态变化
  unsubscribe = onConnectionChange((data) => {
    console.log("🔔 [ConnectionStatusIndicator] 连接状态变化:", data);

    // 如果显示历史，更新历史记录
    if (showHistory.value) {
      updateHistory();
    }

    // 如果有连接问题，自动显示详情
    if (data.status === ConnectionStatus.DISCONNECTED) {
      showDetails.value = true;
    }
  });
});

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe();
  }
});
</script>

<style scoped>
.connection-status-indicator {
  position: relative;
  z-index: 1000;
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 12px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.status-badge:hover {
  background: rgba(0, 0, 0, 0.8);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.status-dot.status-connected {
  background: #00ff00;
  box-shadow: 0 0 8px #00ff00;
  animation: pulse 2s infinite;
}

.status-dot.status-connecting {
  background: #ffaa00;
  box-shadow: 0 0 8px #ffaa00;
  animation: blink 1s infinite;
}

.status-dot.status-reconnecting {
  background: #ff9900;
  box-shadow: 0 0 8px #ff9900;
  animation: blink 0.8s infinite;
}

.status-dot.status-disconnected {
  background: #ff0000;
  box-shadow: 0 0 8px #ff0000;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@keyframes blink {
  0%,
  50%,
  100% {
    opacity: 1;
  }
  25%,
  75% {
    opacity: 0.3;
  }
}

.status-text {
  font-size: 12px;
  color: #fff;
  font-weight: 500;
}

.status-details {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  width: 320px;
  background: rgba(20, 20, 20, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
  overflow: hidden;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.detail-header h4 {
  margin: 0;
  font-size: 14px;
  color: #fff;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #fff;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.close-btn:hover {
  opacity: 1;
}

.detail-content {
  padding: 12px;
}

.connection-item {
  padding: 12px;
  background: rgba(255, 255, 255, 0.03);
  border-radius: 6px;
  margin-bottom: 8px;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.item-label {
  font-size: 13px;
  color: #aaa;
  font-weight: 500;
}

.item-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 600;
}

.item-status.status-ok {
  background: rgba(0, 255, 0, 0.2);
  color: #00ff00;
}

.item-status.status-error {
  background: rgba(255, 0, 0, 0.2);
  color: #ff0000;
}

.item-detail {
  display: flex;
  gap: 8px;
  font-size: 11px;
  margin-top: 4px;
}

.detail-label {
  color: #888;
}

.detail-value {
  color: #ccc;
  flex: 1;
}

.connection-history {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
  color: #aaa;
  font-weight: 500;
}

.clear-btn {
  background: none;
  border: none;
  color: #888;
  font-size: 11px;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 3px;
  transition: all 0.2s;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.history-list {
  max-height: 200px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  gap: 8px;
  padding: 6px 8px;
  font-size: 11px;
  border-radius: 4px;
  margin-bottom: 4px;
  background: rgba(255, 255, 255, 0.02);
}

.history-time {
  color: #888;
  min-width: 90px;
}

.history-type {
  color: #aaa;
  min-width: 30px;
}

.history-status {
  min-width: 30px;
  font-weight: 600;
}

.history-status.connected {
  color: #00ff00;
}

.history-status.disconnected {
  color: #ff0000;
}

.history-reason {
  color: #ccc;
  flex: 1;
}

.action-buttons {
  margin-top: 12px;
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  padding: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(255, 255, 255, 0.3);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
